package com.aios.action.user.iris;

import java.util.List;
import java.util.Locale;

import com.aios.service.ExistValidationEnum;
import com.aios.util.EmailUtil;

public class IrisUserSaveAction extends AbstractIrisUserAction {

	private static final long serialVersionUID = 1L;
	private List<Integer> selectedList;

	public String execute() {
		
		validateIrisUser();

		if (hasErrors()) {
			this.inputPopulate(Locale.JAPAN);
			return INPUT;
		}

		if(!(EmailUtil.chackEmailPattern(irisUser.getEmail()))) {
			addActionError(getText("error.email.invalid"));
			this.editPopulate(Locale.JAPAN);
			return INPUT;
		}
		
		if (getMode() == Mode.ADD) {

			ExistValidationEnum existValidationEnum = irisUserService
					.emailExistValidation(irisUser.getEmail());
			
			if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
				addActionError(getText("error.email.exist"));
				this.inputPopulate(Locale.JAPAN);
				return INPUT;
			}
			
			try {
				irisUserService
						.save(irisUser, getSessionUserVariable().getId());
				irisUser.setId(irisUserService.findIdByEmailAddress(irisUser
						.getEmail()));
				irisUserService.saveGroupList(irisUser, selectedList,
						getSessionUserVariable().getId());
				
				irisUserService.saveIrisData(irisUser,irisData,getSessionUserVariable().getId());

			} catch (Exception e) {
				e.printStackTrace();
				addActionError(getText("error.insert"));
				this.inputPopulate(Locale.JAPAN);
				return INPUT;
			}

		} else if (getMode() == Mode.EDIT) {
			try {
				
				ExistValidationEnum existValidationEnum = irisUserService
						.emailExistValidation(irisUser.getEmail(),irisUser.getId());
				
				if (existValidationEnum != ExistValidationEnum.NOT_EXIST) {
					addActionError(getText("error.email.exist"));
					this.editPopulate(Locale.JAPAN);
					return INPUT;
				}
				
				irisUserService.update(irisUser, getSessionUserVariable()
						.getId());
				irisUserService.updateGroupsList(irisUser, selectedList,
						getSessionUserVariable().getId());
				irisUserService.updateIrisData(irisUser,irisData,getSessionUserVariable().getId());

			} catch (Exception e) {
				// add action error
				e.printStackTrace();
				addActionError(getText("error.update"));
				this.editPopulate(Locale.JAPAN);
				return INPUT;
			}
			// validation
		} else {
			// add action error
			return INPUT;
		}


		return SUCCESS;
	}

	private void validateIrisUser() {
		if (irisUser.getName().isEmpty()) {
			addFieldError("irisUser.name", getText("error.name.empty"));
		}

		if (irisUser.getEmail().isEmpty()) {
			addFieldError("irisUser.email", getText("error.email.empty"));
		}
	}

	public List<Integer> getSelectedList() {
		return selectedList;
	}

	public void setSelectedList(List<Integer> selectedList) {
		this.selectedList = selectedList;
	}

}
